import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_cors import CORS
from flask_jwt_extended import JWTManager
from flask_marshmallow import Marshmallow
from config import Config

db = SQLAlchemy()
login_manager = LoginManager()
jwt = JWTManager()
ma = Marshmallow()

def create_app():
    app = Flask(__name__)
    app.config.from_object(Config)
    
    # 确保上传文件夹存在
    os.makedirs(os.path.join(app.config['UPLOAD_FOLDER'], 'services'), exist_ok=True)
    os.makedirs(os.path.join(app.config['UPLOAD_FOLDER'], 'carousel'), exist_ok=True)
    os.makedirs(os.path.join(app.config['UPLOAD_FOLDER'], 'images'), exist_ok=True)

    # 确保 instance 文件夹存在
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    # 初始化插件
    db.init_app(app)
    login_manager.init_app(app)
    jwt.init_app(app)
    ma.init_app(app)
    CORS(app)

    # 注册蓝图
    from app.routes import auth, main, admin, api, profile
    from app.api_docs import blueprint as api_doc
    app.register_blueprint(auth.bp)
    app.register_blueprint(main.bp)
    app.register_blueprint(admin.bp)
    app.register_blueprint(api.bp)
    app.register_blueprint(profile.bp)
    app.register_blueprint(api_doc)

    # 注册错误处理
    register_error_handlers(app)

    return app

def register_error_handlers(app):
    @app.errorhandler(400)
    def bad_request(e):
        return {'error': 'Bad Request'}, 400

    @app.errorhandler(404)
    def not_found(e):
        return {'error': 'Not Found'}, 404

    @app.errorhandler(500)
    def internal_server_error(e):
        return {'error': 'Internal Server Error'}, 500 